// 定义角色表单字段
import * as roleApi from "@/api/roles";
import {useDataActions} from "@/services/useDataActions";
import {useFormActions} from "@/services/useFormActions";
import {ElMessage} from "element-plus";
import {computed} from "vue";

const roleFields = [
  'id',
  'name',
  'code',
  'description',
  'order_num',
  'status',
  'menu_ids',
  'permission_ids'
]

/**
 * 角色管理的表单操作钩子函数
 * @param {Object} options - 配置选项
 * @param {Function} options.onRoleChange - 当角色数据发生变化时的回调函数
 * @returns {Object} 表单操作接口
 */
export function useRoleFormActions({ onRoleChange = () => {} }) {
    // 使用表单控制逻辑
    const { formVisible, currentFormData, openForm } = useFormActions({
        fields: roleFields
    });

    // 包装原始的 openForm 方法以处理表单类型
    const wrappedOpenForm = (row, type = 'default') => {
        // 默认情况下是编辑操作
        if (type === 'assignMenu') {
            // 处理分配菜单操作
            selectedRoleId.value = row.id;
            menuAssignVisible.value = true;
            return;
        } else if (type === 'assignPermissions') {
            // 处理分配权限操作
            selectedRoleId.value = row.id;
            permissionAssignVisible.value = true;
            return;
        }
        
        // 调用原始的 openForm 方法
        openForm(row, type);
    };

    // 使用数据操作逻辑
    const { handleFormSubmit, handleDelete, handleFieldUpdate } = useDataActions({
        api: {
            create: roleApi.createRole,
            update: roleApi.updateRole,
            delete: roleApi.deleteRole
        },
        onActionSuccess: onRoleChange,
        messages: {
            createSuccess: '角色创建成功',
            updateSuccess: '角色更新成功',
            deleteSuccess: '角色删除成功',
            updateField: '字段更新成功',
            error: '操作失败'
        }
    });

    // 分配菜单给角色
    const assignMenuToRole = async (roleId, menuIds) => {
        try {
            await roleApi.assignMenuToRole(roleId, menuIds);
            ElMessage.success('角色菜单分配成功');
            onRoleChange();
        } catch (error) {
            console.error('分配菜单失败:', error);
            ElMessage.error('分配菜单失败');
        }
    };

    // 分配权限给角色
    const assignPermissionsToRole = async (roleId, permissionIds) => {
        try {
            await roleApi.assignPermissionToRole(roleId, permissionIds);
            ElMessage.success('角色权限分配成功');
            onRoleChange();
        } catch (error) {
            console.error('分配权限失败:', error);
            ElMessage.error('分配权限失败');
        }
    };

    // 向外暴露这些接口
    return {
        formVisible,
        currentFormData,
        openForm: wrappedOpenForm, // 使用包装后的方法
        handleFormSubmit,
        handleDelete,
        handleFieldUpdate,
        assignMenuToRole,
        assignPermissionsToRole
    };
}

// 获取页面列表数据
export const useRoleListData = (roleStore, filter) => {
    // 如果 store 中没有数据，则从 API 获取
    if (!roleStore.rolesList || roleStore.rolesList.length === 0) {
        roleStore.fetchRoles();
    }
    
    // 返回计算属性以支持过滤
    const filteredRoleList = computed(() => {
        let result = roleStore.rolesList;
        if (filter.value.name) {
            result = result.filter(item => item.name.includes(filter.value.name));
        }
        return result;
    });

    return {
        filteredRoleList
    };
}

